﻿using AVISOutBound.SSOServer.Authorization.Members;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVISOutBound.SSOServer.Identity
{
    public class ABGSignInManager : SignInManager<Member>
    {
        public ABGSignInManager(ABGUserManager userManager,
            IHttpContextAccessor contextAccessor,
            IUserClaimsPrincipalFactory<Member> claimsFactory,
            IOptions<IdentityOptions> optionsAccessor,
            ILogger<SignInManager<Member>> logger,
            IAuthenticationSchemeProvider schemes)
            : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
        {

        }

        /// <summary>
        /// 手机快递登录
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <param name="code">短信验证码</param>
        /// <param name="isPersistent"></param>
        /// <param name="rememberClient"></param>
        /// <returns></returns>
        public virtual async Task<SignInResult> PhoneNumberSignInAsync(string phone, string code, bool isPersistent, bool rememberClient)
        {
            var user = this.UserManager.Users.FirstOrDefault(u => u.PhoneNumber == phone);
            if (user == null)
            {
                return SignInResult.Failed;
            }

            var error = await PreSignInCheck(user);
            if (error != null)
            {
                return error;
            }

            if (await UserManager.VerifyTwoFactorTokenAsync(user, "Phone", code))
            {
                // When token is verified correctly, clear the access failed count used for lockout
                await ResetLockout(user);
                await SignInAsync(user, isPersistent);
                return SignInResult.Success;
            }

            // If the token is incorrect, record the failure which also may cause the user to be locked out
            await UserManager.AccessFailedAsync(user);
            return SignInResult.Failed;
        }
    }
}
